package com.itita.ww2.model.building;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Seconds;

import com.itita.ww2.data.BuildingConfig;
import com.itita.ww2.data.PlayerConfig;
import com.itita.ww2.model.enums.ResourceType;
import com.itita.ww2.model.user.DevTime.DevTimeType;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.TimeUtil;

/**
 * 资源建筑
 * @author NorthLan
 *
 */
public class BDResource extends BuildingBase {

	public BDResource(UserProfile userProfile, String code, int level) {
		super(userProfile, code, level);
		// init();
	}

	public BDResource init() {
		userProfile.getTimeManager().addResDevTime(getResType().getValue());
		userProfile.getTimeManager().update();
		return this;
	}

	/**
	 * 获取对应的资源类型
	 */
	public ResourceType getResType() {
		return ResourceType.bdCodeValueOf(this.code);
	}

	/**
	 * 收集资源(返回下一次更新的时间)
	 */
	public synchronized int collectResource() {
		long effect = BuildingConfig.getBDEffect(this.code, this.level);
		int duration = PlayerConfig.getResHarvestDuration();// 资源收获间隔

		String resCode = ResourceType.bdCodeValueOf(this.code).getValue();
		// long userRes = userProfile.getResManager().getResByType(resType);
		// 计算增长数
		DateTime nowTime = TimeUtil.getUtcNow();
		DateTime lastTime = new DateTime(
				userProfile.getTimeManager().getDevTime(DevTimeType.RESOURCE, resCode).getEndTime(), DateTimeZone.UTC); // 上一次更新时间
		int deltaSeconds = Seconds.secondsBetween(lastTime, nowTime).getSeconds();
		if (deltaSeconds < duration) {
			return duration - deltaSeconds;
		} else {
			long deltaRes = effect * deltaSeconds / 60;
			// 更新资源
			userProfile.getResManager().operResWithCheck(resCode, deltaRes);
			// 更新时间
			userProfile.getTimeManager().updateDevTime(DevTimeType.RESOURCE, resCode, nowTime.getMillis());
			userProfile.getTimeManager().update();
			return duration;
		}
	}
}
